﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ykglxt
{
    public partial class Form_YPSCSDZ : Form
    {
        public Form_YPSCSDZ()
        {
            InitializeComponent();
        }

        DataSet ds;
        int firsttime = 0;
        bool empty = true;
        DataRow dr;
        SqlDataAdapter sdaUpdate;
        SqlCommandBuilder scb;
        SqlConnection con;

        private void Form_YPSCSDZ_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“yKGLXTDataSet.Dic_SCS”中。您可以根据需要移动或移除它。
            this.dic_SCSTableAdapter.Fill(this.yKGLXTDataSet.Dic_SCS);
            con = new SqlConnection(PublicUnit.ConnetionString);
            try
            {
                    ds = new DataSet();
                    SqlCommand com = new SqlCommand("INSERT INTO Dic_YPSCSDZ(YPBM,SCS) SELECT BM,'' FROM Dic_YP WHERE BM NOT IN (SELECT YPBM FROM Dic_YPSCSDZ)", con);
                    con.Open();
                    com.ExecuteNonQuery();
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT YP.BM, YP.MC AS 药品名称, YPSCSDZ.SCS, SCS.MC 生产商 FROM Dic_YP YP, Dic_YPSCSDZ YPSCSDZ LEFT " +
                        "JOIN Dic_SCS SCS ON YPSCSDZ.SCS =SCS.BM WHERE YP.BM = YPSCSDZ.YPBM",con);
                    sda.Fill(ds,"SCSDZ");
                    dgvSCSDZ.DataSource = ds.Tables["SCSDZ"].DefaultView;
                    dgvSCSDZ.Columns[2].Visible = false;
                    sdaUpdate = new SqlDataAdapter("SELECT * from Dic_YPSCSDZ", con);
                    scb = new SqlCommandBuilder(sdaUpdate);
                    sdaUpdate.Fill(ds,"Update");
                    ds.Tables["Update"].PrimaryKey = new DataColumn[] { ds.Tables["Update"].Columns[0]};
                    dr = ds.Tables["Update"].NewRow();
            }
            catch(SqlException ex)
            {
                 if (ex.Number == 18456)
                    MessageBox.Show("网络故障，请稍后再试！", "警告" + ex.Number, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show("保存成功，已保存"  +  sdaUpdate.Update(ds.Tables["Update"]).ToString().Trim() + "条修改记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (SqlException ex)
            {
                if (ex.Number == 2627)
                    MessageBox.Show("保存失败，编码必须是唯一的，请查看是否存在重复的编码！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (ex.Number == 515)
                    MessageBox.Show("保存失败，编码不能为空，请查看是否存在记录缺填编码！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    MessageBox.Show("保存失败，网络故障，请稍后再试！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            int rowindx = (dgvSCSDZ.SelectedRows[0].Index - 1 + dgvSCSDZ.RowCount) % dgvSCSDZ.RowCount;
            dgvSCSDZ.ClearSelection();
            dgvSCSDZ.Rows[rowindx].Selected = true;
            dgvSCSDZ.FirstDisplayedScrollingRowIndex = dgvSCSDZ.SelectedRows[0].Index;
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            int rowIndex = (dgvSCSDZ.SelectedRows[0].Index + 1) % dgvSCSDZ.RowCount;
            dgvSCSDZ.ClearSelection();
            dgvSCSDZ.Rows[rowIndex].Selected = true;
            dgvSCSDZ.FirstDisplayedScrollingRowIndex = rowIndex;
            if (rowIndex < dgvSCSDZ.FirstDisplayedScrollingRowIndex)
            {
                dgvSCSDZ.FirstDisplayedScrollingRowIndex = rowIndex;
            }
            else if (!dgvSCSDZ.Rows[rowIndex].Displayed)
            {
                dgvSCSDZ.FirstDisplayedScrollingRowIndex++;
            }

        }

        private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            dgvSCSDZ.ClearSelection();
            dgvSCSDZ.Rows[0].Selected = true;
            dgvSCSDZ.FirstDisplayedScrollingRowIndex = 0;
        }

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            dgvSCSDZ.ClearSelection();
            dgvSCSDZ.Rows[dgvSCSDZ.RowCount - 2].Selected = true;
            dgvSCSDZ.FirstDisplayedScrollingRowIndex = dgvSCSDZ.RowCount - 1;

        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            dgvSCSDZ.ClearSelection();
            dgvSCSDZ.Rows[dgvSCSDZ.NewRowIndex].Selected = true;
            dgvSCSDZ.FirstDisplayedScrollingRowIndex = dgvSCSDZ.NewRowIndex;
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除该记录？", "请选择", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                dgvSCSDZ.Rows.RemoveAt(this.dgvSCSDZ.CurrentRow.Index);
                ds.Tables["Update"].Rows.RemoveAt(dgvSCSDZ.CurrentCell.RowIndex);
            }
        }


        private void dgvYPDW_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.tbxYPDW.Text = this.dgvYPDW.CurrentRow.Cells[0].Value.ToString();
                this.dgvYPDW.Visible = false;
                for (int i = 0; i < this.dgvSCSDZ.Rows.Count; i++)
                {
                    if (tbxYPDW.Text == this.dgvSCSDZ[this.dgvSCSDZ.Columns[0].Index, this.dgvSCSDZ.Rows[i].Index].Value.ToString())
                    {
                        this.dgvSCSDZ.ClearSelection();
                        this.dgvSCSDZ.Rows[i].Selected = true;
                        this.dgvSCSDZ.CurrentCell = this.dgvSCSDZ.Rows[i].Cells[0];
                        return;
                    }
                }
            }

        }

        private void tbxYPDW_KeyDown(object sender, KeyEventArgs e)
        {
            if (empty)
                return;

            if (e.KeyCode == Keys.Down)
            {
                dgvYPDW.Focus();
                if (dgvYPDW.CurrentRow.Index + 1 < dgvYPDW.Rows.Count)
                {
                    dgvYPDW.CurrentCell = dgvYPDW[0, dgvYPDW.CurrentRow.Index + 1];
                }
            }

            if (e.KeyCode == Keys.Enter)
            {
                this.tbxYPDW.Text = this.dgvYPDW.CurrentRow.Cells[0].Value.ToString();
                this.dgvYPDW.Visible = false;
            }
        }

        private void tbxYPDW_TextChanged(object sender, EventArgs e)
        {
            try
            {
                this.dgvYPDW.Top = this.tbxYPDW.Top + this.tbxYPDW.Height;

                if (firsttime == 0)
                {
                    firsttime = 1;
                    empty = getData();
                }

                if (empty)
                    return;

                if (tbxYPDW.Text == " ")
                {
                    if (ds.Tables["YPDW"].DefaultView.Count != 0)
                        dgvYPDW.Visible = true;

                }
                else
                {
                    string dh = "编码 like '" + tbxYPDW.Text.Trim() + "%' or 药品名称 like '%" + tbxYPDW.Text.Trim() + "%'" + " or 助记码 like '" + tbxYPDW.Text.Trim() + "%'";
                    ds.Tables["YPDW"].DefaultView.RowFilter = dh.ToString();
                }
                if (ds.Tables["YPDW"].DefaultView.Count != 0)
                {
                    dgvYPDW.Visible = true;
                    dgvYPDW.CurrentCell = dgvYPDW[0, 0];
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private bool getData()
        {
            bool res;
            try
            {
                res = false;

                using (SqlConnection conn = new SqlConnection(PublicUnit.ConnetionString))
                {
                    try
                    {
                        conn.Open();
                        SqlDataAdapter da = new SqlDataAdapter("select bm as '编码',zjf as '助记码',mc AS '药品名称',gg AS '规格',sccs AS '生产产家'  from dic_yp", conn);
                        ds = new DataSet();
                        da.Fill(ds, "YPDW");
                        this.dgvYPDW.DataSource = ds.Tables["YPDW"].DefaultView;
                        res = false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("error!" + ex.ToString());
                        res = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("error!" + ex.ToString());
                res = true;
            }
            return res;
        }

        private void tbxYPDW_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (tbxYPDW.ReadOnly) // 只读, 不处理 
                return;

            if ((int)e.KeyChar <= 32) // 特殊键(含空格), 不处理 
                return;

            if (!char.IsDigit(e.KeyChar) && !char.IsLetter(e.KeyChar)) // 非数字字母键, 放弃该输入 
            {
                e.Handled = true;
                return;
            }
        }

        private void dgvYPDW_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.tbxYPDW.Text = this.dgvYPDW.CurrentRow.Cells[0].Value.ToString();
            this.dgvYPDW.Visible = false;
            for (int i = 0; i < this.dgvSCSDZ.Rows.Count; i++)
            {
                if (tbxYPDW.Text == this.dgvSCSDZ[this.dgvSCSDZ.Columns[0].Index, this.dgvSCSDZ.Rows[i].Index].Value.ToString())
                {
                    this.dgvSCSDZ.ClearSelection();
                    this.dgvSCSDZ.Rows[i].Selected = true;
                    this.dgvSCSDZ.CurrentCell = this.dgvSCSDZ.Rows[i].Cells[0];
                    return;
                }
            }
        }

        private void dgvSCSDZ_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            tbxYPBM.Text = dgvSCSDZ.Rows[dgvSCSDZ.CurrentCell.RowIndex].Cells[0].Value.ToString().Trim();
            cbxSCS.SelectedValue = dgvSCSDZ.Rows[dgvSCSDZ.CurrentCell.RowIndex].Cells[2].Value.ToString().Trim();
        }

        private void cbxSCS_SelectedIndexChanged(object sender, EventArgs e)
        { 
            if(cbxSCS.Focused)
            {
                dgvSCSDZ.Rows[dgvSCSDZ.CurrentCell.RowIndex].Cells[3].Value = cbxSCS.Text;
                dr = ds.Tables["Update"].Rows.Find(dgvSCSDZ.Rows[dgvSCSDZ.CurrentCell.RowIndex].Cells[0].Value.ToString().Trim());
                dr[1] = cbxSCS.SelectedValue.ToString().Trim();
            }
        }

    }
}
